<template>
  <div style="max-width: 600px; margin: 50px ; ">
    <el-card>
      <template #header>
        <div class="card-header">
          <span>修改密码</span>
        </div>
      </template>

      <el-form :model="form" :rules="rules" ref="formRef" label-width="100px">
        <el-form-item label="旧密码" prop="oldPassword">
          <el-input type="password" v-model="form.oldPassword" show-password placeholder="请输入旧密码" />
        </el-form-item>

        <el-form-item label="新密码" prop="newPassword">
          <el-input type="password" v-model="form.newPassword" show-password placeholder="请输入新密码" />
        </el-form-item>

        <el-form-item label="确认新密码" prop="confirmPassword">
          <el-input
            type="password"
            v-model="form.confirmPassword"
            show-password
            placeholder="请再次输入新密码"
          />
        </el-form-item>

        <el-form-item>
          <el-button type="primary" @click="submitForm">提交</el-button>
          <el-button @click="resetForm">重置</el-button>
        </el-form-item>
      </el-form>
    </el-card>
  </div>
</template>

<script setup>
import { reactive, ref } from 'vue'
import { ElMessage } from 'element-plus'
import request from '@/utils/request'
import router from '@/router'
import { encryptPassword } from '@/utils/crypto';
const formRef = ref()

const form = reactive({
  oldPassword: '',
  newPassword: '',
  confirmPassword: '',
})

const rules = {
  oldPassword: [{ required: true, message: '请输入旧密码', trigger: 'blur' }],
  newPassword: [
    { required: true, message: '请输入新密码', trigger: 'blur' },
    {
      validator: (rule, value, callback) => {
        const strongPasswordReg =
          /^(?=.*[A-Za-z])(?=.*\d)(?=.*[!@#$%^&*()_+[\]{};':"\\|,.<>/?]).{6,}$/
        if (!strongPasswordReg.test(value)) {
          callback(
            new Error('密码必须包含字母、数字和特殊字符，且不少于6位')
          )
        } else {
          callback()
        }
      },
      trigger: 'blur',
    },
  ],
  confirmPassword: [
    { required: true, message: '请确认新密码', trigger: 'blur' },
    {
      validator: (rule, value, callback) => {
        if (value !== form.newPassword) {
          callback(new Error('两次输入的新密码不一致'))
        } else {
          callback()
        }
      },
      trigger: 'blur',
    },
  ],
}


const submitForm = () => {
  formRef.value.validate(valid => {
    if (valid) {
      request.post('/forget', {
        password: encryptPassword(form.oldPassword),
        newPassword: encryptPassword(form.newPassword),
      }).then((res) => {
        if (res.code === 200) {
          ElMessage.success('密码修改成功')
          // 重置表单
          resetForm()
          localStorage.removeItem('user_code')
          router.push('/login')
        } else {
          ElMessage.error('密码修改失败')
        }
      })

    }
  })
}

const resetForm = () => {
  formRef.value.resetFields()
}
</script>
